﻿namespace Arms.Application.Modules.Reports
{
    using Arms.Application.Modules.Reports.DTOs;
    using Arms.Application.Services;
    using Arms.Domain;
    using Arms.Domain.Modules.Orders;
    using Arms.Framework;
    using System;
    using System.Data.Entity;
    using System.Linq;

    public class QuickReportService : ServiceBase, IQuickReportService
    {
        public QuickReportService(IUnitOfWork uow) : base(uow) { }

        public double GetAverageDailyIncome()
        {
            var results = base.UnitOfWork.Repository<Order>().Query()
                                                             .Where(x => x.OrderState == OrderState.Invoiced)
                                                             .GroupBy(x => DbFunctions.TruncateTime(x.Updated.Value))
                                                             .ToList();

            if (results != null && results.Count > 0)
            {
                return results.Select(x => x.Average(y => y.SubTotal)).Average();
            }
            else
            {
                return 0;
            }                                     
        }

        public double GetDailyIncome()
        {
            return base.UnitOfWork.Repository<Order>().Query()
                                                      .Where(x => DbFunctions.TruncateTime(x.Updated.Value) == DbFunctions.TruncateTime(DateTime.UtcNow))
                                                      .Where(x => x.OrderState != OrderState.Void || x.OrderState != OrderState.Processing)
                                                      .ToList()
                                                      .Sum(x => x.SubTotal);
        }

        public int GetDailyOrderCount()
        {
            return base.UnitOfWork.Repository<Order>().Query()
                                                      .Where(x => DbFunctions.TruncateTime(x.Updated.Value) == DbFunctions.TruncateTime(DateTime.UtcNow))
                                                      .ToList()
                                                      .Count();
        }
        /// <summary>
        /// Gets the quick report dto.
        /// </summary>
        /// <returns></returns>
        public QuickReportDTO GetQuickReport()
        {
            return new QuickReportDTO()
            {
                AverageDailyIncome = this.GetAverageDailyIncome(),
                DailyIncome = this.GetDailyIncome(),
                DailyOrderCount = this.GetDailyOrderCount()
            };
        }
    }
}
